<template>
  <div class="count-box">
    <button @click="handleSub" class="minus">-</button>
    <input :value="value" @change="handleChange" class="inp" type="text">
    <button @click="handleAdd" class="add">+</button>
  </div>
</template>

<script setup>
import { ref, defineEmits,defineProps } from 'vue'
const props = defineProps({
  value: {
    type: Number, // 替换为适当的数据类型
    required: true, // 根据您的需求选择 true 或 false
    default: 1
  }
})
const emits = defineEmits(['input'])
function handleSub() {
  if (value.value <= 1) {
    return
  }
  emits('input', value.value - 1)
}
function handleAdd() {
  emits('input', value.value + 1)
}

function handleChange() {

  const num = +e.target.value // 转数字处理 (1) 数字 (2) NaN

  // 输入了不合法的文本 或 输入了负值，回退成原来的 value 值
  if (isNaN(num) || num < 1) {
    e.target.value = value.value
    return
  }
  emits('input', num)
}
</script>

<style lang="less" scoped>
.count-box {
  width: 110px;
  display: flex;

  .add,
  .minus {
    width: 30px;
    height: 30px;
    outline: none;
    border: none;
    background-color: #efefef;
  }

  .inp {
    width: 40px;
    height: 30px;
    outline: none;
    border: none;
    margin: 0 5px;
    background-color: #efefef;
    text-align: center;
  }
}
</style>
